package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.counseling.model.common.exception.ServiceException;
import com.campus.counseling.entity.ConsultationRecord;
import com.campus.counseling.entity.Counselor;
import com.campus.counseling.model.dto.RecordRateDTO;
import com.campus.counseling.model.mapper.ConsultationRecordMapper;
import com.campus.counseling.model.mapper.CounselorMapper;
import com.campus.counseling.service.ConsultationRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ConsultationRecordServiceImpl extends ServiceImpl<ConsultationRecordMapper, ConsultationRecord> implements ConsultationRecordService {

    private final CounselorMapper counselorMapper;

    @Override
    public IPage<ConsultationRecord> getRecordList(Long page, Long size, ConsultationRecord query) {
        return baseMapper.selectRecordList(new Page<>(page, size), query);
    }

    @Override
    @Transactional
    public void addRecord(ConsultationRecord record) {
        save(record);
    }

    @Override
    @Transactional
    public void updateRecord(ConsultationRecord record) {
        if (!updateById(record)) {
            throw new ServiceException("更新失败，记录可能不存在");
        }
    }

    @Override
    @Transactional
    public void deleteRecord(Long id) {
        if (!removeById(id)) {
            throw new ServiceException("删除失败，记录可能不存在");
        }
    }

    @Override
    public ConsultationRecord getRecordDetail(Long id) {
        ConsultationRecord record = getById(id);
        if (record == null) {
            throw new ServiceException("记录不存在");
        }
        return record;
    }

    @Override
    public ConsultationRecord getRecordByAppointmentId(Long appointmentId) {
        return this.getOne(
            new LambdaQueryWrapper<ConsultationRecord>()
                .eq(ConsultationRecord::getAppointmentId, appointmentId)
                .eq(ConsultationRecord::getDeleted, 0)
        );
    }

    @Override
    public Integer getCompletedConsultsCount(Long counselorId) {
        return Math.toIntExact(this.lambdaQuery()
            .eq(ConsultationRecord::getCounselorId, counselorId)
            .eq(ConsultationRecord::getDeleted, 0)
            .count());
    }

    @Override
    public Integer getServedStudentsCount(Long counselorId) {
        return Math.toIntExact(this.lambdaQuery()
            .eq(ConsultationRecord::getCounselorId, counselorId)
            .eq(ConsultationRecord::getDeleted, 0)
            .groupBy(ConsultationRecord::getStudentId)
            .count());
    }

    @Override
    public List<ConsultationRecord> getPendingRecords(Long counselorId) {
        return this.lambdaQuery()
            .eq(ConsultationRecord::getCounselorId, counselorId)
            .eq(ConsultationRecord::getDeleted, 0)
            .isNull(ConsultationRecord::getMainIssue)  // 主要问题为空表示未完成
            .list();
    }

    @Override
    @Transactional
    public void rateRecord(RecordRateDTO rateDTO) {
        // 更新咨询记录的评分
        ConsultationRecord record = this.lambdaQuery()
            .eq(ConsultationRecord::getCounselorId, rateDTO.getCounselorId())
            .isNull(ConsultationRecord::getRating)  // 未评分的记录
            .last("LIMIT 1")  // 获取最近一条
            .one();
        
        if (record == null) {
            throw new ServiceException("没有找到可评分的咨询记录");
        }
        
        // 更新记录评分
        record.setRating(rateDTO.getRating());
        updateById(record);
        
        // 重新计算咨询师的平均评分
        Double avgRating = this.lambdaQuery()
            .eq(ConsultationRecord::getCounselorId, rateDTO.getCounselorId())
            .isNotNull(ConsultationRecord::getRating)
            .select(ConsultationRecord::getRating)
            .list()
            .stream()
            .mapToDouble(ConsultationRecord::getRating)
            .average()
            .orElse(5.0);
        
        // 通过user_id查询counselor_info表
        Counselor counselor = counselorMapper.selectOne(
            new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getUserId, rateDTO.getCounselorId())
        );
        
        if (counselor == null) {
            throw new ServiceException("咨询师不存在");
        }
        
        counselor.setRating(avgRating);
        counselorMapper.updateById(counselor);
    }

}